#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_libxml2_fun_008.py
@Time:      2024/02/23 11:12:50
@Author:    hongfeng
@Version:   1.0
@Contact:   wb-zhf668260@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    hongfeng
"""

import os
from common.basetest import LocalTest
class Test(LocalTest):
    """
    See tc_libxml2_fun_008.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "libxml2-devel"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > delete_html.c <<EOF
#include <stdio.h>
#include <libxml/HTMLparser.h>
#include <libxml/HTMLtree.h>
#include <string.h>

// 删除指定名称的元素节点
void removeNodesByTagName(xmlNodePtr rootNode, const xmlChar* nodeName) {
    xmlNode *cur_node = NULL;

    for (cur_node = rootNode; cur_node; cur_node = cur_node->next) {
        if (cur_node->type == XML_ELEMENT_NODE) {
            printf("Element name: %s\\n", cur_node->name);
            if (cur_node->type == XML_ELEMENT_NODE && !xmlStrcmp(cur_node->name, nodeName)) {
                // 解除节点与DOM树的链接
                xmlUnlinkNode(cur_node);
                // 释放节点资源
                xmlFreeNode(cur_node);
            }
        }
        // 递归处理子节点
        removeNodesByTagName(cur_node->children, nodeName);
    }
}

int main() {
    // 初始化libxml2库
    xmlInitParser();

    // 加载HTML文件
    const char *filename = "test_008.html";
    htmlDocPtr doc = htmlReadFile(filename, NULL, HTML_PARSE_RECOVER | HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING);
    if (doc == NULL) {
        fprintf(stderr, "Failed to parse %s\\n", filename);
        return 1;
    }
    // 获取文档的根节点
    xmlNodePtr root_element = xmlDocGetRootElement(doc);

    // 删除所有名为"targetTag"的节点
    xmlChar *targetTagName = (xmlChar *)"p";
    removeNodesByTagName(root_element, targetTagName);

    // 保存修改后的文档
    int result = htmlSaveFileEnc("deleted.html", doc, "UTF-8");
    if (result < 0) {
        fprintf(stderr, "Failed to save the modified file\\n");
    }

    // 清理内存
    xmlFreeDoc(doc);
    xmlCleanupParser();

    return 0;
}
"""
        self.cmd(cmdline)
        self.cmd("gcc -o delete_html delete_html.c `xml2-config --cflags --libs`")
        file_dir = os.path.dirname(__file__)
        self.cmd(f"cp {file_dir}/test.html ./test_008.html")

    def test(self):
        self.cmd("./delete_html")
        ret_c,ret_o = self.cmd("cat deleted.html")
        self.assertTrue("Hello, World!" not in ret_o, 'check output error.')
        
    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm delete_html.c delete_html test_008.html deleted.html")
